import 'dart:async';
import 'dart:typed_data';

import 'package:flutter/cupertino.dart';

class MessageMerger {
  final Duration duration;
  final Function(Uint8List data) notifier;

  DateTime notifyTime;

  MessageMerger({
    this.duration = const Duration(milliseconds: 30),
    @required this.notifier,
  });

  final List<int> dataContainer = [];

  void addData(Uint8List data) {
    dataContainer.addAll(data.toList());
    final notifyTime = DateTime.now().add(duration);
    this.notifyTime = notifyTime;
    Timer(duration, () {
      if (this.notifyTime == notifyTime) {
        notifier(Uint8List.fromList(dataContainer));
        dataContainer.clear();
      }
    });
  }
}
